import {
  Get,
  Post,
  Param,
  Delete,
  UseInterceptors,
  UploadedFiles,
  DefaultValuePipe,
  ParseIntPipe,
  Body,
} from '@nestjs/common';
import { FileService } from './file.service';
import { FilesInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiOperation } from '@nestjs/swagger';
import { diskStorage } from 'multer';
import { appConfig } from '../../config/config';
import { GetUser } from '../auth/get-user.decorator';
import { User } from '../user/entities/user.entity';
import { GetFileFilterDto } from './dto/getFileFilterDto';
import { Pagination } from '../utils/paginate';
import { WitAdmin } from '../auth/wit.admin';
import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator';

@WitAdmin('upload')
export class FileController {
  constructor(private readonly fileService: FileService) {}
  @Post('/upload')
  @UseInterceptors(
    FilesInterceptor('files', null, {
      storage: diskStorage({
        destination: `${__dirname}${appConfig.filePath}`,
        filename: (req, file, cb) => {
          const randomName = Math.floor(Date.now() / 1000); // 文件名+前缀 时间戳（秒）
          cb(null, `${randomName}${file.originalname}`);
        },
      }),
    }),
  )
  @ApiConsumes('multipart/form-data')
  @ApiOperation({
    summary: '上传文件,支持多文件上传',
  })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        files: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  uploadFile(@UploadedFiles() files, @GetUser() user: User): Promise<string> {
    return this.fileService.create(files, user);
  }

  @Post('/getFileList')
  @ApiOperation({
    summary: '获取所有文件信息',
  })
  // @ApiImplicitParam({
  //   name: 'pageNum',
  //   required: false,
  // })
  // @ApiImplicitParam({
  //   name: 'pageSize',
  //   required: false,
  // })
  findAll(
    @Body() getFileFilterDto: GetFileFilterDto,
    @Param('pageNum', new DefaultValuePipe(0), ParseIntPipe) pageNum: number,
    @Param('pageSize', new DefaultValuePipe(0), ParseIntPipe) pageSize: number,
  ): Promise<Pagination<File>> {
    const page = {
      page: pageNum,
      limit: pageSize > 100 ? 100 : pageSize,
    };
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    return this.fileService.findAll(getFileFilterDto, page);
  }

  @Get('/getFile/:id')
  @ApiOperation({
    summary: '获取单个文件信息',
  })
  findOne(@Param('id') id: string) {
    return this.fileService.findOne(id);
  }
  @ApiOperation({
    summary: '删除文件',
  })
  @Delete('/deleteFile/:id')
  remove(@Param('id') id: string) {
    return this.fileService.remove(id);
  }
}
